<template>
  <!-- 搜索区域 -->
  <div class="search-container">
    <el-input
      v-model="fileName"
      placeholder="请输入文件名搜索"
      style="width: 300px"
      clearable
      @clear="handleSearch"
    >
      <template #append>
        <el-button @click="handleSearch">
          <el-icon><Search /></el-icon>
        </el-button>
      </template>
    </el-input>
  </div>

  <!-- 表格区域 -->
  <el-table :data="list" style="width: 100%" border stripe>
    <el-table-column prop="name" label="名称" min-width="300" />
    <el-table-column prop="duration" label="时长" width="120" align="center" />
    <el-table-column label="得分" width="100" align="center">
      <template #default="scope">
        <el-tag v-if="scope.row.score" type="success">{{
          scope.row.score
        }}</el-tag>
        <span v-else>-</span>
      </template>
    </el-table-column>
    <el-table-column
      prop="createdTime"
      label="上一次时间"
      width="180"
      align="center"
    >
      <template #default="scope">
        {{ formatDate(scope.row.createdTime) }}
      </template>
    </el-table-column>
    <el-table-column label="操作" align="center">
      <template #default="scope">
        <el-button type="primary" icon="EditPen" @click="handlePlay(scope.row)"
          >开始练习</el-button
        >
      </template>
    </el-table-column>
  </el-table>

  <!-- 分页 -->
  <div class="pagination-container">
    <el-pagination
      background
      v-model:current-page="currentPage"
      layout="prev, pager, next"
      :total="total"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { Search } from "@element-plus/icons-vue";
import audioApi from "@/api/audio/index";
import { useRouter } from "vue-router";

const fileName = ref("");
const list = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

const router = useRouter();

// 获取列表数据
const getList = () => {
  audioApi
    .getListForTest(fileName.value, currentPage.value, pageSize.value)
    .then((res) => {
      list.value = res.data;
    });
  audioApi.getTotal(fileName.value).then((res) => {
    total.value = res.data;
  });
};

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1;
  getList();
};

// 页码改变
const handleCurrentChange = (val) => {
  currentPage.value = val;
  getList();
};

// 播放处理
const handlePlay = (item) => {
  // 处理播放逻辑，可以跳转到练习页面
  router.push({
    path: "/learning/listening/practice",
    query: { id: item.id },
  });
};

// 日期格式化
const formatDate = (dateStr) => dateStr.replace("T", " ");

onMounted(() => {
  getList();
});
</script>

<style scoped>
.search-container {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 可以添加一些表格行的悬停效果 */
:deep(.el-table__row:hover) {
  cursor: pointer;
  background-color: #f5f7fa !important;
}
</style>
